<template>
  <div class="modal-card">
    <div class="modal-header">
      <div class="modal-title-section">
        <i class="fas fa-file-medical modal-icon"></i>
        <div>
          <h2 class="modal-title">电子处方详情</h2>
          <p class="modal-subtitle">处方号: {{ prescription?.id }}</p>
        </div>
      </div>
      <button type="button" class="btn-close" @click="$emit('close')">
        <i class="fas fa-times"></i>
      </button>
    </div>

    <div class="modal-content">
      <!-- 处方信息卡片 -->
      <div class="info-card">
        <h3 class="info-card-title">
          <i class="fas fa-info-circle"></i>
          处方信息
        </h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">开具医生</span>
            <span class="info-value">{{ prescription?.doctorName }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">科室</span>
            <span class="info-value">{{ prescription?.department }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">开具时间</span>
            <span class="info-value">{{ formatTime(prescription?.createTime) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">当前状态</span>
            <span class="info-value status-value" :class="prescription?.status">
              {{ getStatusText(prescription?.status) }}
            </span>
          </div>
          <div class="info-item">
            <span class="info-label">处方号</span>
            <span class="info-value">{{ prescription?.id }}</span>
          </div>
        </div>
      </div>

      <!-- 患者信息卡片 -->
      <div class="info-card">
        <h3 class="info-card-title">
          <i class="fas fa-user-injured"></i>
          患者信息
        </h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">姓名</span>
            <span class="info-value">{{ prescription?.patientName }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">性别</span>
            <span class="info-value">{{ prescription?.patientGender }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">年龄</span>
            <span class="info-value">{{ prescription?.patientAge }}岁</span>
          </div>
          <div class="info-item full-width">
            <span class="info-label">身份证号</span>
            <span class="info-value">{{ prescription?.patientIdCard }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">预约号</span>
            <span class="info-value">{{ prescription?.resId }}</span>
          </div>
        </div>
      </div>

      <!-- 药品清单卡片 -->
      <div class="info-card">
        <h3 class="info-card-title">
          <i class="fas fa-pills"></i>
          药品清单
          <span class="medicines-count">({{ prescription?.medicines.length }}种)</span>
        </h3>
        <div class="medicines-list">
          <div
            v-for="(medicine, index) in prescription?.medicines"
            :key="index"
            class="medicine-item"
          >
            <div class="medicine-main">
              <span class="medicine-icon">{{ medicine.icon }}</span>
              <div class="medicine-details">
                <h4 class="medicine-name">{{ medicine.name }}</h4>
                <span class="medicine-spec">{{ medicine.specification }}</span>
              </div>
            </div>
            <div class="medicine-quantity">
              <span class="quantity">×{{ medicine.quantity }}</span>
            </div>
            <div class="medicine-pricing">
              <span class="unit-price">¥{{ medicine.price }}</span>
              <span class="total-price">¥{{ (medicine.price * medicine.quantity).toFixed(2) }}</span>
            </div>
          </div>
        </div>
        <div class="total-section">
          <span class="total-label">总计金额:</span>
          <span class="total-amount">¥{{ calculateTotalAmount(prescription) }}</span>
        </div>
      </div>

      <!-- 库存检查卡片 -->
      <div v-if="prescription?.status !== 'completed'" class="info-card">
        <h3 class="info-card-title">
          <i class="fas fa-clipboard-check"></i>
          库存检查
        </h3>
        <div class="stock-check-list">
          <div
            v-for="medicine in prescription?.medicines"
            :key="medicine.id"
            class="stock-check-item"
          >
            <div class="stock-medicine">
              <span class="medicine-name">{{ medicine.name }}</span>
              <span class="required-quantity">需要 {{ medicine.quantity }} 份</span>
            </div>
            <div class="stock-status" :class="getStockStatusClass(medicine)">
              <span class="current-stock">库存 {{ getMedicineStock(medicine.id) }}</span>
              <span class="status-text">{{ getStockStatusTextForMedicine(medicine) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="modal-footer">
      <div class="footer-actions">
        <button
          v-if="prescription?.status === 'pending'"
          class="btn btn-process"
          @click="handleProcess"
          :disabled="!canProcessPrescription"
        >
          <i class="fas fa-play-circle"></i>
          处理药方
        </button>
        <button
          v-if="prescription?.status === 'processing'"
          class="btn btn-complete"
          @click="$emit('complete')"
        >
          <i class="fas fa-check-circle"></i>
          完成发药
        </button>
        <button class="btn btn-secondary" @click="$emit('close')">
          <i class="fas fa-times"></i>
          关闭
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import request from '@/utils/request'

// 定义props
const props = defineProps({
  prescription: {
    type: Object,
    required: true
  },
  medicines: {
    type: Array,
    required: true
  }
})

// 定义事件
const emit = defineEmits(['process', 'complete', 'close'])

// 处理药方方法
const handleProcess = async () => {
  try {
    // 发送预约号到后端
    await request({
      url: '/api/resMed/process',
      method: 'post',
      params: {
        resId: String(props.prescription.id)
      }
    });

    // 成功后触发原有事件
    emit('process')
  } catch (error) {
    console.error('处理处方时出错:', error)
  }
}

// 计算属性
const canProcessPrescription = computed(() => {
  if (!props.prescription) return false
  return props.prescription.medicines.every(medicine => {
    const stock = getMedicineStock(medicine.id)
    return stock >= medicine.quantity
  })
})

// 方法
const getMedicineStock = (medicineId) => {
  const medicine = props.medicines.find(item => item.id === medicineId)
  return medicine ? medicine.stock : 0
}

const getStockStatusClass = (medicine) => {
  const stock = getMedicineStock(medicine.id)
  if (stock === 0) return 'out-of-stock'
  if (stock < medicine.quantity) return 'low-stock'
  return 'in-stock'
}

const getStockStatusTextForMedicine = (medicine) => {
  const stock = getMedicineStock(medicine.id)
  if (stock === 0) return '缺货'
  if (stock < medicine.quantity) return '库存不足'
  return '库存充足'
}

const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'processing': '处理中',
    'completed': '已完成'
  }
  return statusMap[status] || status
}

const formatTime = (timeString) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

const calculateTotalAmount = (prescription) => {
  if (!prescription || !prescription.medicines) return 0
  return prescription.medicines.reduce((total, medicine) => {
    return total + (medicine.price * medicine.quantity)
  }, 0).toFixed(2)
}

const debugMedicineMapping = () => {
  if (props.prescription && props.medicines) {
    console.log('处方药品:', props.prescription.medicines);
    console.log('库存药品:', props.medicines);

    props.prescription.medicines.forEach(med => {
      const match = props.medicines.find(item => item.id === med.id);
      console.log(`药品 ${med.name}(ID:${med.id}) 匹配结果:`, match ? `库存${match.stock}` : '未找到');
    });
  }
}

</script>

<style scoped>
.modal-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 24px;
  background: linear-gradient(135deg, #f8f9fc 0%, #f0f2f5 100%);
  border-bottom: 1px solid #e8eaf0;
}

.modal-title-section {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.modal-icon {
  font-size: 28px;
  color: #4a6cf7;
  margin-top: 4px;
}

.modal-title {
  font-size: 24px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0 0 4px 0;
}

.modal-subtitle {
  font-size: 14px;
  color: #8f9bb3;
  margin: 0;
}

.btn-close {
  background: none;
  border: none;
  font-size: 20px;
  color: #8f9bb3;
  cursor: pointer;
  padding: 4px;
  transition: all 0.3s;
}

.btn-close:hover {
  color: #1a1a1a;
  transform: scale(1.1);
}

.modal-content {
  padding: 24px;
  max-height: 60vh;
  overflow-y: auto;
}

.info-card {
  background: #f8f9fc;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #e8eaf0;
}

.info-card:last-child {
  margin-bottom: 0;
}

.info-card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 16px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid #e8eaf0;
}

.info-card-title i {
  color: #4a6cf7;
}

.medicines-count {
  font-size: 14px;
  color: #8f9bb3;
  font-weight: normal;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-label {
  font-size: 14px;
  font-weight: 600;
  color: #555;
}

.info-value {
  font-size: 16px;
  color: #1a1a1a;
}

.status-value.pending {
  color: #fa5252;
  font-weight: 600;
}

.status-value.processing {
  color: #f59f00;
  font-weight: 600;
}

.status-value.completed {
  color: #0ca678;
  font-weight: 600;
}

/* 药品清单样式 */
.medicines-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}

.medicine-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e8eaf0;
}

.medicine-main {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.medicine-details {
  display: flex;
  flex-direction: column;
}

.medicine-name {
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 4px 0;
}

.medicine-spec {
  font-size: 12px;
  color: #8f9bb3;
}

.medicine-quantity {
  margin: 0 20px;
}

.quantity {
  font-weight: 600;
  color: #4a6cf7;
}

.medicine-pricing {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.unit-price {
  font-size: 14px;
  color: #8f9bb3;
}

.total-price {
  font-weight: 600;
  color: #1a1a1a;
}

.total-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 2px solid #e8eaf0;
}

.total-label {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.total-amount {
  font-size: 24px;
  font-weight: 700;
  color: #4a6cf7;
}

/* 库存检查样式 */
.stock-check-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stock-check-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e8eaf0;
}

.stock-medicine {
  display: flex;
  flex-direction: column;
}

.stock-medicine .medicine-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.required-quantity {
  font-size: 12px;
  color: #8f9bb3;
}

.stock-status {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
}

.stock-status.in-stock {
  background: #e7f7ef;
  color: #0ca678;
}

.stock-status.low-stock {
  background: #fff9e6;
  color: #f59f00;
}

.stock-status.out-of-stock {
  background: #ffe3e3;
  color: #fa5252;
}

.current-stock {
  font-size: 14px;
}

.status-text {
  font-size: 12px;
}

/* 模态框底部按钮 */
.modal-footer {
  padding: 20px 24px;
  background: #f8f9fc;
  border-top: 1px solid #e8eaf0;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  border: none;
  border-radius: 10px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.btn-process {
  background: #4a6cf7;
  color: white;
}

.btn-process:hover:not(:disabled) {
  background: #3a5ce5;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(74, 108, 247, 0.3);
}

.btn-process:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-complete {
  background: #0ca678;
  color: white;
}

.btn-complete:hover {
  background: #0b956b;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(12, 166, 120, 0.3);
}

.btn-secondary {
  background: #e8eaf0;
  color: #555;
}

.btn-secondary:hover {
  background: #d0d0d0;
  transform: translateY(-2px);
}
</style>